package com.orangelife.mobile.myhouse.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHandler;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.common.jump.HouseJumper;
import com.orangelife.mobile.myhouse.biz.HouseHttpBiz;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 非户主填写邀请码的界面
 * <p>
 * Created by 吴格非 on 2015/11/13.
 */
public class HouseCodeActivity extends OrangeLifeBaseActivity {
    @Bind(R.id.etVerifyCode)
    EditText etVerifyCode;
    @Bind(R.id.btnCommit)
    Button btnCommit;
    @Bind(R.id.tvResend)
    TextView tvResend;
    @Bind(R.id.tvTip)
    TextView tvTip;
    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;

    private String applicationID;
    /**Activit 名称**/
    final  String MODULE_NAME="/IA/UPOWriteIAInfo/UPOWritePOMsgCode";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_code);
        ButterKnife.bind(this);
        getIntentInfo();
        if (applicationID == null) {
            ToastHelper.getInstance().displayToastLong("对不起，没有获取到认证ID，请重试");
        }
        requestCodeEffectTime();
        initTitle();

    }


    /**
     * 数据采集体不要删除
     * @return
     */
    public Map<String,Object> getDataTrack(){
        Map<String,Object> map=new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }
    private void getIntentInfo() {
        applicationID = getIntent().getStringExtra("applicationID");
    }

    private void initTitle() {
        tvTitle.setText("身份认证");
    }

    private void requestCommit() {
        String code = etVerifyCode.getText().toString();
        if (!StringUtil.isContainBlank(applicationID, code)) {
            showDialog(this);
            HouseHttpBiz.commitVerifyCode(new VolleyHttpUtil.ResponseCallBack() {
                @Override
                public void handleResponse(JSONObject response, int errCode) {
                    closeDialog();
                    if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                        jumpToCertOk();
//                        requestMyHouseList();
                    }else{
                        Map<String,Object> map=new HashMap<String, Object>();
                        map.put("submitFailReason","验证码错误");
                        dataTrackClick("btnSubmit",map);
                    }
                }
            }, applicationID, code);
        } else {
            ToastHelper.getInstance()._toast("先填写验证码...");
        }
    }

    private void jumpToCertOk() {
        HouseJumper.jumpToCertOk(this);
        finish();
    }

//    private void requestMyHouseList() {
//        HouseHttpBiz.getMyHousesListForSave();
//    }

    private void requestResend() {
        showDialog(this);
        startTimer("60");
        HouseHttpBiz.requestHostCodeAgain(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                closeDialog();
                if (!OrangeErrorHandler.getInstance().isSuccess(response, getString(R.string.send_sms_fail), getString(R.string.send_sms_success))) {
                    stopTimer();
                }
            }
        }, applicationID);
    }

    private void requestCodeEffectTime() {
        HouseHttpBiz.getCodeEffectTime(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                String time = HouseHttpBiz.handleCodeEffectTime(response);
                //FIXME StringFormat
                tvTip.setText("验证码已发送至您填写的户主手机,有效时间是，" + time + "，请及时与户主联系");
            }
        }, applicationID);
    }

    @OnClick({R.id.ib_title_left, R.id.btnReApp, R.id.btnCommit, R.id.tvResend})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnCommit:
                dataTrackClick("btnSubmit",null);
                requestCommit();
                break;
            case R.id.btnReApp:
                HouseJumper.jumpToCert(HouseCodeActivity.this, "true");
                break;
            case R.id.tvResend:
                requestResend();
                break;
            case R.id.ib_title_left:
                CurryApplication.getInstance().finishActivity(this);
                break;
        }
    }

    private void disableCode() {
        etVerifyCode.setText("");
        tvResend.setEnabled(false);
    }

    private void enableCode() {
        tvResend.setEnabled(true);
        tvResend.setText(getResources().getString(
                R.string.send_again));
    }

    private CountDownHandler countDownHandler;
    private boolean isCountDown;

    //初始化
    private void startTimer(String second) {
        disableCode();
        if (countDownHandler == null) {
            countDownHandler = new CountDownHandler();
            countDownHandler.isOnlySecond(true);
            countDownHandler.isUseCustomCountDownInfo(true);
            countDownHandler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {
                    enableCode();
                }

                @Override
                public void onCountDown(String currentSecond) {
                    tvResend.setText(String.format(getString(R.string.sms_obtain_again), currentSecond));
                }
            });
        }
        countDownHandler.startTimer(second);
    }

    private void stopTimer() {
        if (countDownHandler != null && isCountDown) {
            countDownHandler.stopTimer();
            isCountDown = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }
}
